package com.imooc.rsa;


import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * Description: 过滤器
 * Author: gzj
 * Date: 2024/4/24 13:41
 */
public class ResponseDataFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = ((HttpServletRequest) request).getRequestURI();
//        如果是非 multipart/form-data 类型（文件）的请求，则进行解密处理，否则不处理
        if ("/common/upload".equals(uri)
                || "/login".equals(uri)
                || "/captchaImage".equals(uri)
                || "/rsa/key".equals(uri)) {
            chain.doFilter(request, response);
        } else {

            HttpServletRequest requests =  (HttpServletRequest) request;
            String requestBody = getRequestBody(requests);
            //解密请求报文

            String requestBodyMw = "";
            if(StringUtils.isNotBlank(requestBody)){
                try {
                    requestBodyMw = new String(RsaUtil2.decrypt(RsaUtil2.decryptBASE64(requestBody)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            WrapperedRequest wrapRequest = new WrapperedRequest( (HttpServletRequest) request, requestBodyMw);
            WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
            chain.doFilter(wrapRequest, wrapResponse);
            byte[] data = wrapResponse.getResponseData();
            // 加密返回报文.如果是/tool/gen/batchGenCode，代码下载接口，则不加密
            if(!"/tool/gen/batchGenCode".equals(uri)){
                String responseBodyMw = null;
                try {
                    responseBodyMw = RsaUtil2.encryptBASE64(RsaUtil2.encrypt(data));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                response.getOutputStream().write(responseBodyMw.getBytes());
            }else {
                response.getOutputStream().write(data);
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private String getRequestBody(HttpServletRequest req) {
        try {
            BufferedReader reader = req.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            return json;
        } catch (IOException e) {
            System.out.println("请求体读取失败"+e.getMessage());
        }
        return "";
    }
}
